<template>
  <div :class="$style.container" v-loading.fullscreen.lock="loading">
    <el-card>
      <div slot="header">
        <span>用户列表</span>
        <btnList :isAdd="true" :isEdit="true" @btn_list="handleBtnClick" :currentRowData="selectData"/>
      </div>
      <el-form :model="searchForm" :inline="true" style="margin-top:10px;margin-bottom:20px;">
        <el-form-item label="手机号:" :label-width="formLabelWidth">
          <el-input v-model="searchForm.phone" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" :label-width="formLabelWidth">
          <el-input v-model="searchForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item style="margin-left:50px;">
          <el-button type="primary" @click.stop="handleSearchClick">查询</el-button>
          <el-button type="primary" @click.stop="handleResetClick">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="tableData" stripe style="width: 100%" border>
        <el-table-column label="序号">
          <template slot-scope="scope">
            <el-radio v-model="selectData" :label="scope.row">{{''}}</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="昵称" min-width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="180">
        </el-table-column>
        <el-table-column prop="status1" label="状态" min-width="180">
        </el-table-column>
        <el-table-column prop="name" label="操作" min-width="160">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleResetPwd(scope.$index, scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <PaginationNumber :page="page" @pagination="paginationChange" />
    </el-card>

    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="showModal">
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item label="昵称:" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" :label-width="formLabelWidth" prop="phone" required>
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态:" :label-width="formLabelWidth">
          <el-radio-group v-model="form.status">
            <el-radio :label="false">禁用</el-radio>
            <el-radio :label="true">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否允许登录后台:" label-width="150px">
          <el-radio-group v-model="form.type">
            <el-radio label="02">不允许</el-radio>
            <el-radio label="01">允许</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showModal = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitFormClick('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

   
  </div>
</template>

<script>
import { signPwd, validatePhone } from "../../../../utils/config";

export default {
  data() {
    let validPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {

        if (!validatePhone(value)) {
          callback(new Error("请输入有效的手机号"));
        }else {
           callback();
        }
      }
    };
    return {
      tableData: [],
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showModal: false,
      title: "",
      formLabelWidth: "120px",
      form: {},
      selectData: {},
      rules: {
        name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            validator: validPhone,
            trigger: "blur"
          }
        ]
      },
      searchForm: {
        email:'',
        phone: ''
      }
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      try {
        this.loading = true;
        let obj = {
          page: this.page.current,
          size: this.page.size,
        }
        if (this.searchForm.email) {
          obj.email = this.searchForm.email
        }
        if (this.searchForm.phone) {
          obj.phone = this.searchForm.phone
        }
        let res = await this.$http.get(`/users/getUserLists`,obj);
        this.loading = false;
        this.page.total = res.data.total
        this.tableData = res.data.uLists.map(item => {
          if (item.status) {
            item.status1 = "启用";
          } else {
            item.status1 = "禁用";
          }
          return item;
        });
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 重置密码
    async handleResetPwd(index, row) {
      try {
        this.loading = true;
        await this.$http.post(`/users/resetPwd`, {
          password: signPwd("123456789"),
          usid: row.userId
        });
        this.init();
      } catch (err) {
        console.log(err);
      }
    },
    handleBtnClick(type) {
      if (type === "add") {
        this.title = "新增用户";
        this.form = {
          type: "02",
          status: true,
          password: signPwd("123456789"),
        };
        this.showModal = true;
      } else if (type === "edit") {
        this.title = "编辑用户";
        this.form = { ...this.selectData };
        if (Object.keys(this.form).length > 0) {
           this.showModal = true;
        }
      }
    },
    // 提交模态框的表单
    handleSubmitFormClick(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.title === "新增用户") {
            this.addUser();
          } else if (this.title === "编辑用户") {
            this.updateUser();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 编辑用户
    async updateUser() {
      try {
        let obj = {
          usid: this.form.userId,
          status: this.form.status,
          type: this.form.type,
          name: this.form.name,
          email: this.form.email,
          phone: this.form.phone
        };
        this.showModal = false;
        let res = await this.$http.post(`/users/updateUser`, obj);
        if (res.code === 0) {
          this.resetForm()
          this.message('success','编辑成功')
          this.init();
        }
      } catch (err) {
        console.log("update user :", err);
      }
    },
    /**
     * 添加用户
     */
    async addUser() {
      try {
        let obj = {
          status: this.form.status,
          type: this.form.type,
          name: this.form.name,
          email: this.form.email,
          phone: this.form.phone,
          password: this.form.password
        };
        this.showModal = false;
        let res = await this.$http.post(`/users/addUser`, obj);
        if (res.code === 0) {
          this.message('success','新增成功')
          this.resetForm()
          this.init();
        }
      } catch (err) {
        console.log("add user:", err);
      }
    },
    // 分页
    paginationChange(current, size) {
      this.page.current = current;
      this.page.size = size;
      this.init();
    },
    // 查询
    handleSearchClick () {
      this.page.current = 1
      this.init()
    },
    resetForm () {
      this.form = {
        name: '',
        phone: '',
        email: ''
      }
    },
    // 重置btn
    handleResetClick () {
      this.searchForm.email = ''
      this.searchForm.phone = ''
      this.init()
    }
  }
};
</script>

<style lang='scss' module>
.container {
  padding: 20px;
}
</style>